/**
 * Copyright (C), 2018-2020, 龙腾出行
 * FileName: LoginInterceptor
 * Author:   zhouw
 * Date:     2020/7/23 20:41
 * Description: 登陆拦截器
 * History:
 * <author>          <time>          <version>          <desc>
 * zhouw           20:41                       描述
 */
package cn.com.dragonpass.psystem.common.interceptor;

import cn.com.dragonpass.common.utils.SpringContextHolder;
import cn.com.dragonpass.common.utils.StringUtils;
import cn.com.dragonpass.pmodel.common.DataEntity;
import cn.com.dragonpass.pmodel.common.enums.RedisKeyEnum;
import cn.com.dragonpass.pmodel.user.UserDto;
import cn.com.dragonpass.psystem.common.configuration.SessionContext;
import cn.com.dragonpass.psystem.common.redis.JedisUtils;
import cn.com.dragonpass.psystem.common.util.JwtUtils;
import cn.com.dragonpass.psystem.common.util.RequestUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Locale;
/**
 * 登陆拦截器
 *
 * @author zhouw
 * @create 2020/7/23
 * @since 1.0.0
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

      //白名单访问的路径(比如:注册登录等)
    private String[] includeUris = new String[]{"/user/login","/user/getCaptcha2","/user/verifyAccount","/user/resetPwd","/user/h5/transmit"};

    private MessageSource messageSource= SpringContextHolder.getBean(MessageSource.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        String requestURI = request.getRequestURI().replaceAll("/+", "/");
        String code = request.getHeader("Code");
        logger.info("requestURI:{}", requestURI);
        if(StringUtils.isEmpty(token)&&"GET".equals(request.getMethod())){
            token=request.getParameter("Token");
        }

        boolean needFilter = RequestUtils.isNeedFilter(requestURI, includeUris);
        //不需要过滤直接传给Controller
        if (!needFilter) {
            return true;
        }

        if (StringUtils.isEmpty(token)) {
            return makeRespone(response,"user.no.permission","02");
        }
        //        //发布时间
//        Date date1=JwtUtils.getIssuedAt(token);
//
//        //过期时间
//        Date date=JwtUtils.getExpiration(token);


//        String time=JwtUtils.refreshToken(token);

//        if(JwtUtils.isExpired(token)){
//            throw new UserFriendlyException("token.isExpired",00);
//        }

        Claims claim = JwtUtils.getClaim(token);
        if (claim == null) {
            return makeRespone(response,"permission.check.fail","02");
        }


        String uid = null;
        try {
            uid = JwtUtils.getOpenId(token);
        } catch (Exception e) {
            return makeRespone(response,"login.fail","02");
        }

        String JsonString = JedisUtils.getInstance().get(RedisKeyEnum.UserId.keyBuilder() + uid);
        if (!StringUtils.isNotBlank(JsonString)) {
            return makeRespone(response,"permission.check.fail","02");
        }
        UserDto.UserVo userVo = JSONObject.parseObject(JsonString, UserDto.UserVo.class);
        if (userVo == null) {
            return makeRespone(response,"login.fail","02");
            //throw new BussinessException("login.fail",00);
        }
//        List<AccPermissionDto.AddInput> permission = userVo.getPermissions().stream().filter(w ->
//                requestURI.equals(w.getApipath()) && code.equals(w.getCode())).collect(Collectors.toList());
//        if (permission.isEmpty()) {
//            throw new UserFriendlyException("module.isnot.permission");
//        }
        //用户id放到上下文 可以当前请求进行传递
        request.setAttribute(SessionContext.USER_ID_KEY, uid);

        //重置token时间，三小时
        JedisUtils.getInstance().expire(RedisKeyEnum.UserId.keyBuilder() + uid, 3600 * 24);
        JwtUtils.refreshToken(token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    /**
     * 自定义返回
     * */
    public boolean makeRespone(HttpServletResponse response,String Message,String State) {

        try {
            if (response.isCommitted()){ return false;}
            response.reset();
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            Locale locale = LocaleContextHolder.getLocale();
            DataEntity<?> resultData = new DataEntity<>();
            resultData.setState(State);
            resultData.setMsg(messageSource.getMessage(Message, null, Message, locale));

            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(resultData));

            pw.flush();


        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}